package com.west.common.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.widget.FrameLayout;

import com.west.common.common.R;

/**
 * @author hanyulang
 * @date 2018/12/14
 */
public class RatioLayout extends FrameLayout {

    private float mRatio = 1.0f;
    private static final int FLAG_WIDTH = 1;
    private static final int FLAG_HEIGHT = 2;
    private int mFlag;

    public RatioLayout(@NonNull Context context) {
        this(context, null);
    }

    public RatioLayout(@NonNull Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public RatioLayout(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(attrs);
    }

    private void init(AttributeSet attrs){
        if(attrs == null) return;
        TypedArray array = getContext().obtainStyledAttributes(attrs, R.styleable.RatioLayout);
        mFlag = array.getInt(R.styleable.RatioLayout_ratio_flag, FLAG_WIDTH);
        mRatio = array.getFloat(R.styleable.RatioLayout_layout_ratio, mRatio);
        array.recycle();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int width, height;
        if(mFlag == FLAG_WIDTH){
            width = MeasureSpec.getSize(widthMeasureSpec);
            height = (int) ((float)width * mRatio);
            heightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);
        }else if(mFlag == FLAG_HEIGHT){
            height = MeasureSpec.getSize(heightMeasureSpec);
            width = (int) ((float)height / mRatio);
            widthMeasureSpec = MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY);
        }
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

}
